using Pomelo.DotNetClient;
using LitJson;
using UnityEngine;
using System;
using System.Collections.Generic;
public class PomeloManager : MonoBehaviour
{
    private static PomeloManager _instance;
    /**
     * Pomelo管理器单例
     */
    public static PomeloManager GetInstance()
    {
        return _instance;
    }
    void Awake()
    {
        _instance = this;
        UnityEngine.Object.DontDestroyOnLoad(gameObject);
    }
    void Start()
    {
    }
    public void ClearRoots()
    {
        receiverBehaviours = null;
    }
    public string host = "127.0.0.1";
    public int port = 1990;
    public PomeloClient pomelo;
    public void Connect(string host = null, int port = -1)
    {
        var h = host == null ? this.host : host;
        var p = port == -1 ? this.port : port;
        if (pomelo != null)
        {
            pomelo.close();
        }
        pomelo = new PomeloClient();
        InitMessages();
        pomelo.Connect(h, p, "", delegate ()
        {
            if (pomelo.IsConnected)
            {
                _OnSocketOpen();
            }
        },
        delegate ()
        {
            _OnSocketClose();
        }
        );
    }
    private List<PomeloBehaviour> receiverBehaviours = new List<PomeloBehaviour>();
    private Dictionary<string, string> receiverMap;
    public void AddReceiverBehaviour(PomeloBehaviour receiverBehaviour)
    {
        this.receiverBehaviours.Add(receiverBehaviour);
    }
    public void RemoveReceiverBehaviour(PomeloBehaviour receiverBehaviour)
    {
        this.receiverBehaviours.Remove(receiverBehaviour);
    }
    public void RegReceiverMap(Dictionary<string, string> receiverMap)
    {
        this.receiverMap = receiverMap;
    }
    private string[] messages;
    public void RegistMessages(string[] messages)
    {
        this.messages = messages;
    }
    private void InitMessages()
    {
        for (var i = 0; i < messages.Length; i++)
        {
            this.On(messages[i]);
        }
    }
    public void On(string message)
    {
        pomelo.on(message, delegate (JsonData response)
         {
             var methodName = receiverMap == null ? "OnSocketMessage" : receiverMap[(string)response["cmd"]];
             if ((int)response["code"] == 200)
             {
                 Debug.Log("【广播】收到消息：" + message + " 数据：" + response.ToJson() + "，时间戳：" + Time.time);
                 for (var i = 0; i < receiverBehaviours.Count; i++)
                 {
                     receiverBehaviours[i].SendMessage(methodName, response["data"]);
                 }
                 SendMessage(methodName, response, SendMessageOptions.DontRequireReceiver);
             }
             else
             {
                 Debug.Log("【广播】消息出错：" + message + " 错误码：" + response["code"] + " 数据：" + response.ToJson() + "，时间戳：" + Time.time);
                 for (var i = 0; i < receiverBehaviours.Count; i++)
                 {
                     receiverBehaviours[i].SendMessage(methodName + "_Error", response);
                 }
                 SendMessage(methodName, response, SendMessageOptions.DontRequireReceiver);
             }
         });
    }
    private void _OnSocketOpen()
    {
        pomelo.HandShake(new JsonData(), delegate (JsonData data)
        {
            // if ((int)data["code"] == 200)
            // {
            Debug.Log("网络已连接");
            for (var i = 0; i < receiverBehaviours.Count; i++)
            {
                receiverBehaviours[i].SendMessage("OnSocketOpen", null);
            }
            SendMessage("OnSocketOpen", null, SendMessageOptions.DontRequireReceiver);
            // }
            // else
            // {
            //     _OnSocketClose();
            // }
        });
    }
    private void _OnSocketClose()
    {
        Debug.Log("网络已断开");
        for (var i = 0; i < receiverBehaviours.Count; i++)
        {
            receiverBehaviours[i].SendMessage("OnSocketClose", null);
        }
        SendMessage("OnSocketClose", null, SendMessageOptions.DontRequireReceiver);
    }
    public void Update()
    {
        if (pomelo != null)
        {
            pomelo.poll();
        }
    }
    public void Request(string route, Action<JsonData> action)
    {
        Debug.Log("【发送】发送消息：" + route + " 数据：{}，时间戳：" + Time.time);
        pomelo.request(route, delegate (JsonData response)
        {
            Debug.Log("【回调】收到消息：" + route + " 数据：" + response.ToJson() + "，时间戳：" + Time.time);
            action(response);
        });
    }

    public void Request(string route, JsonData msg, Action<JsonData> action)
    {
        Debug.Log("【发送】发送消息：" + route + " 数据：" + msg.ToJson() + "，时间戳：" + Time.time);
        pomelo.request(route, msg, delegate (JsonData response)
        {
            Debug.Log("【回调】收到消息：" + route + " 数据：" + response.ToJson() + "，时间戳：" + Time.time);
            action(response);
        });
    }
    public void Close()
    {
        if (pomelo != null)
        {
            pomelo.close();
        }
    }
}